//package com.glsc.ngateway.flowable.config;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import lombok.RequiredArgsConstructor;
//import org.springframework.core.Ordered;
//import org.springframework.core.annotation.Order;
//import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.http.HttpStatus;
//import org.springframework.http.MediaType;
//import org.springframework.stereotype.Component;
//
//import javax.servlet.*;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//import java.util.concurrent.TimeUnit;
//
//@Component
//@RequiredArgsConstructor
//@Order(Ordered.HIGHEST_PRECEDENCE)
//public class RateLimiterFilter implements Filter {
//    private final RedisTemplate<String, String> redisTemplate;
//    private final ObjectMapper objectMapper;
//    private final static String rateLimiterKey = "amproduct:flowable:";
//
//    @Override
//    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
//            throws IOException, ServletException {
//
//        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
//        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
//        //获取接口请求路径
//        String servletPath = httpServletRequest.getServletPath();
//        //直接递增
//        Long increment = this.redisTemplate.opsForValue().increment(rateLimiterKey + servletPath);
//        if (increment != null && increment > 10) {
//            //超过5次的限制
//            this.redisTemplate.delete(rateLimiterKey + servletPath);
//            httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
//            httpServletResponse.setCharacterEncoding("utf-8");
//            httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
//            httpServletResponse.getWriter().print(objectMapper.writeValueAsString("超过访问频率限制"));
//            return;
//        } else if (increment != null && increment == 1) {
//            //第一次请求时，一定要记得给key设置过期时间
//            this.redisTemplate.expire(rateLimiterKey + servletPath, 3, TimeUnit.SECONDS);
//        }
//        chain.doFilter(httpServletRequest, httpServletResponse);
//    }
//}
